<?php

class ListingsController extends AppController {

    var $name = 'Listings';
    var $uses = array('Listing', 'Review', 'Location', 'Category');
    var $paginate = array(
        'Listing' => array (
            'limit' => 10,
            'order' => array(
                'Listing.id' => 'DESC'
            )
        )
    );

    /**
     * Listing Model
     *
     * @var Listing
     */
    var $Listing;

    /**
     * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
     */
    function __initPublicActions() {
    	if($this->Auth->user('id')){
	        $this->Auth->allow(array(
	            'init_db',
	            'search',
	            'submit',
	            'submit_getsubcategories',
	            'submit_getfirstchildcategories',
	            'submit_getsublocations',
	            'submit',
	            'review',
	            'claim',              
              'ajaxFilterSearch'

	        ));
        } else {
        	$this->Auth->allow(array(
	            'init_db',
	            'search',

	            'submit_getsubcategories',
	            'submit_getfirstchildcategories',
	            'submit_getsublocations',
              'ajaxFilterSearch'

	        ));
        }
    }

    function beforeFilter() {
        parent::beforeFilter();

        $this->__initPublicActions();

        if (isset($this->Security) && ($this->action == 'submit')) {
            $this->Security->enabled = false;
        }
    }

    function init_db() {
        $this->loadModel('Group');

        $group = & $this->Group;

        //------------- root [id=1]
        $group->id = 1;

        $this->Acl->allow($group, 'controllers');
        //------------/ root [id=1]
        //------------- user [id=2]
        $group->id = 2;

        $this->Acl->allow($group, 'controllers/Listings/review');
        $this->Acl->allow($group, 'controllers/Listings/submit');
        $this->Acl->allow($group, 'controllers/Listings/submit_getsubcategories');
        $this->Acl->allow($group, 'controllers/Listings/submit_getfirstchildcategories');
        $this->Acl->allow($group, 'controllers/Listings/submit_getsublocations');
        //------------/ user [id=2]

        echo "all done";
        exit;
    }

    public function getStreetViewImage($lat,$lng){
        $url='http://maps.googleapis.com/maps/api/streetview?size=300x300&location=';
        $query = $url . $lat . ',' . $lng . '&sensor=false&key=AIzaSyAdFxNC0zLmfLU6y0rKRky5DxAV10GYtYs';
        $geocode = base64_encode(file_get_contents($query));
        return $geocode;

    }
    
    function search() {
        if (!empty($this->data)) {
            $searchstr = $this->data['Listings']['search'];
            $searchstr2 = $this->data['Listings']['nearby'];
            $this->set('searchstring', $this->data['Listings']['search']);
            $this->set('searchnearby', $this->data['Listings']['nearby']);


            $conditions2 = array(
                'conditions' => array(
                    'or' => array(
                        "ListingTag.name like" => "%$searchstr%"
                    )
                )
            );
            //$this->set('ListingsTags', $this->Listing->ListingTag->find('all', $conditions2));
            $result1 = $this->Listing->ListingTag->find('all', $conditions2);
            $i = 0;
            $nearbylatlong = $this->getLatLong($searchstr2);
            if ($nearbylatlong == ',') {
                $final = $result1;
            } else {

                foreach ($result1 as $row1) {
                    if (isset($row1['Listing'][0]['address_1'])) {
                        $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing'][0]['address_1']), $nearbylatlong);
                        if ($distance < 20000) {
                            $row1['distance'] = $distance;
                            $row1['nearbylatlong'] = $nearbylatlong;
                            $final[$i] = $row1;
                            $i++;
                        }
                    }
                }
            }
            $this->set('ListingsTags', $final);
            $categories = $this->Listing->Category->find('all', array(
                'conditions' => array(
                    'Category.name' => $searchstr
                )
                    ));
            $i = 0;
            foreach ($categories as $row) {
                $final3[$i] = $row;
                $test = $this->__generateTreeListRecursive($row['Category']['id']);
                foreach ($test as $rowr) {
                    $rowr = str_replace('-', '', $rowr);
                    $conditions = array(
                        'conditions' => array(
                            'or' => array(
                                "Listing.title LIKE" => "%$rowr%",
                                "Listing.description LIKE" => "%$rowr%",
                                "Category.name LIKE" => "%$rowr%"
                            )
                        )
                    );
                    $result3 = $this->Listing->find('all', $conditions);
                }
                $i++;
            }
            $conditions = array(
                'conditions' => array(
                    'or' => array(
                        "Listing.title LIKE" => "%$searchstr%",
                        "Listing.description LIKE" => "%$searchstr%",
                        "Category.name LIKE" => "%$searchstr%"
                    )
                )
            );
            $result2 = $this->Listing->find('all', $conditions);
            $i = 0;
            if ($nearbylatlong == ',') {
                $final2 = $result2;
            } else {
                foreach ($result2 as $row1) {
                    if ($row1['Listing']['address_1'] !== '') {
                        $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing']['address_1']), $nearbylatlong);
                        if ($distance < 20000) {
                            $row1['distance'] = $distance;
                            $row1['nearbylatlong'] = $nearbylatlong;
                            $final2[$i] = $row1;
                            $i++;
                        }
                    }
                }
                foreach ($result3 as $row1) {
                    if ($row1['Listing']['address_1'] !== '') {
                        $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing']['address_1']), $nearbylatlong);
                        if ($distance < 20000) {
                            $row1['distance'] = $distance;
                            $row1['nearbylatlong'] = $nearbylatlong;
                            $final2[$i] = $row1;
                            $i++;
                        }
                    }
                }
            }
            
            //tuannguyen2042 for FILTER 
                       
            $locIds = array();
            $catIds = array();
            foreach($final2 as $listing){              
              $locIds[] = $listing['Listing']['location_id'];
              $catIds[] = $listing['Listing']['category_id'];
            }
            $locIds = array_unique($locIds);
            $catIds = array_unique($catIds);
            
            /*
            $ls = array();            
            foreach($locIds as $locId){
              $ls[] = $this->getRootParentLocation($locId);
            }
            $ls = array_unique($ls);
            
            $cs = array();
            foreach($catIds as $catId){
              $cs[] = $this->getRootParentCategory($catId);
            }
            $cs = array_unique($cs);
            */
            
            $locations = $this->Location->find('all', array('conditions' => array('Location.id' => $locIds), 'recursive' => 0));
            $categories = $this->Category->find('all', array('conditions' => array('Category.id' => $catIds), 'recursive' => 0));
            
            $this->set(compact('locations', 'categories'));
            //$this->set('locations', $ls);
            //$this->set('categories', $cs)            
            //end
                        
            

            //$this->set('Listings', $this->Listing->find('all', $conditions));
            $this->set('Listings', $final2);
            $this->set('nbll', $nearbylatlong);
        }
    }
    
    
    //tuannguyen2042 FOR FILTER
    private function getRootParentCategory($category_id) {
        $root = $this->Category->getPath($category_id);
        if (count($root) > 0)
            return $root[0]['Category']['id'];

        return $category_id;
    }

    private function getRootParentLocation($location_id) {
        $root = $this->Location->getPath($location_id);
        if (count($root) > 0)
            return $root[0]['Location']['id'];

        return array();
    }
    
    public function ajaxFilterSearch(){
      $this->autoRender = false;
      
      $catIds = array();
      $locIds = array();            
      
      foreach($this->params['url'] as $name => $value){
        if (strpos($name, 'cat') === 0)
          $catIds[] = $value;
        elseif (strpos($name, 'loc') === 0)
          $locIds[] = $value;
      }         
      
      if (count($catIds) == 1)
        $catIds = $catIds[0];
        
      if (count($locIds) == 1)
        $locIds = $locIds[0]; 
        
      //$this->set(compact('locIds', 'catIds'));            
      
                 
      $searchstr = $this->params['url']['searchstr'];
      $searchstr2 = $this->params['url']['searchnearby'];   
      
      $final = array();
      if (!empty($searchstr) || !empty($searchstr2)){      
        if (!empty($searchstr)){
          $conditions2 = array('conditions' => array('OR' => array("ListingTag.name LIKE" => "%$searchstr%")));
                    
          $result1 = $this->Listing->ListingTag->find('all', $conditions2);
          $i = 0;
          $nearbylatlong = $this->getLatLong($searchstr2);
          if ($nearbylatlong == ',') {
            $final = $result1;
          } 
          else {
            foreach ($result1 as $row1) {
              if (isset($row1['Listing'][0]['address_1'])) {
                $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing'][0]['address_1']), $nearbylatlong);
                if ($distance < 20000) {
                  $row1['distance'] = $distance;
                  $row1['nearbylatlong'] = $nearbylatlong;
                  $final[$i] = $row1;
                  $i++;
                }
              }
            }
          }
        }          
        $this->set('ListingsTags', $final);
             
        $categories = array();         
        if (count($catIds) > 0){
          if (!empty($searchstr)){
            $categories = $this->Listing->Category->find('all', array(
              'conditions' => array(
                'Category.name LIKE' => "%$searchstr%",
                'Category.id' => $catIds
              )
            ));
          }
          else{
            $categories = $this->Listing->Category->find('all', array(
              'conditions' => array(               
                'Category.id' => $catIds
              )
            ));
          }
        }
        else{
          if (!empty($searchstr)){
            $categories = $this->Listing->Category->find('all', array(
              'conditions' => array(
                'Category.name LIKE' => "%$searchstr%"             
              )
            ));
          }          
        }
          
        $i = 0;
        foreach ($categories as $row) {
          $final3[$i] = $row;
          $test = $this->__generateTreeListRecursive($row['Category']['id']);
          foreach ($test as $rowr) {
            $rowr = str_replace('-', '', $rowr);
            $conditions = array(
                'conditions' => array(
                  'or' => array(
                    "Listing.title LIKE" => "%$rowr%",
                    "Listing.description LIKE" => "%$rowr%",                    
                  )
                )
            );
            $result3 = $this->Listing->find('all', $conditions);
          }
          $i++;
        }
        
        $orArray = array();
        if (!empty($searchstr)){
          $orArray = array("Listing.title LIKE" => "%$searchstr%", "Listing.description LIKE" => "%$searchstr%");
        }
                  
        if (count($locIds) == 0 && count($catIds) == 0){
            $conditions = array(
              'conditions' => array(
                'or' => $orArray
              )
            );
        }
        else{
          if (empty($locIds)){
            $orArray = array_merge($orArray, array("Listing.category_id" => $catIds));
            $conditions = array(
              'conditions' => array(
                'or' => $orArray                   
              )
            );          
          }
          elseif (empty($catIds)){
            $orArray = array_merge($orArray, array("Listing.location_id" => $locIds));                
            $conditions = array(
                'conditions' => array(
                  'or' => $orArray
                )
            );
          }
          else{
            $orArray = array_merge($orArray, array("Listing.category_id" => $catIds, "Listing.location_id" => $locIds));
            $conditions = array(              
              'conditions' => array(
                'or' => $orArray
              )
            );
          }          
        }
        
        //print_r($conditions);
          
        $result2 = $this->Listing->find('all', $conditions);
        $i = 0;
        if ($nearbylatlong == ',') {
          $final2 = $result2;
        } 
        else {
          foreach ($result2 as $row1) {
              if ($row1['Listing']['address_1'] !== '') {
                $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing']['address_1']), $nearbylatlong);
                if ($distance < 20000) {
                  $row1['distance'] = $distance;
                  $row1['nearbylatlong'] = $nearbylatlong;
                  $final2[$i] = $row1;
                  $i++;
                }
              }
          }
            
          foreach ($result3 as $row1) {
              if ($row1['Listing']['address_1'] !== '') {
                $distance = $this->distanceGeoPoints($this->getLatLong($row1['Listing']['address_1']), $nearbylatlong);
                if ($distance < 20000) {
                  $row1['distance'] = $distance;
                  $row1['nearbylatlong'] = $nearbylatlong;
                  $final2[$i] = $row1;
                  $i++;
                }
              }
          }
        }
          
        $this->set('Listings', $final2);
        $this->set('nbll', $nearbylatlong);
          
        $this->render('/listings/ajaxFilterSearch', 'ajax');                        
      }
    }
    //end
    
    

    function getLatLong($address) {
        $key = 'AhOqe3nZwtht6ytH1npIOIKRV2ppLtyYDwMjoa7ZMUrkWk8rEClXWnBUYwihqGb6';
        $prepAddr = str_replace(' ', '+', $address);
        //$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
        $geocode = file_get_contents('http://dev.virtualearth.net/REST/v1/Locations?q=' . $prepAddr . '&key=' . $key);
        //return $geocode;
        $output = json_decode($geocode);
        $rs = $output->resourceSets[0];
        $rs = $rs->resources[0];
        $rs = $rs->geocodePoints[0];
        $rs = $rs->coordinates;
        $latitude = $rs[0];
        $longitude = $rs[1];
        return $latitude . ',' . $longitude;
    }

    function distanceGeoPoints($latlng1, $latlng2) {

        $temp = explode(',', $latlng1);
        $lat1 = $temp[0];
        $lng1 = $temp[1];
        $temp = explode(',', $latlng2);
        $lat2 = $temp[0];
        $lng2 = $temp[1];
        $earthRadius = 3958.75;

        $dLat = deg2rad($lat2 - $lat1);
        $dLng = deg2rad($lng2 - $lng1);


        $a = sin($dLat / 2) * sin($dLat / 2) +
                cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
                sin($dLng / 2) * sin($dLng / 2);
        $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
        $dist = $earthRadius * $c;

        // from miles
        $meterConversion = 1609;
        $geopointDistance = $dist * $meterConversion;

        return $geopointDistance;
    }

    function submit($id = null, $claim = null, $listing=null) {

    	if($id && $claim && $claim == 'claim'){
    		$listing = $this->Listing->read(null, $id);
    		$claimees_str = $listing['Listing']['claim_by_users'];
    		$claimees = explode(',', $claimees_str);
    		foreach($claimees as $claim){
    			if($this->Auth->user('id') == $claim){
    				$this->Session->setFlash('Your have already claimed.');
    				$this->redirect($this->referer());
    			}
    		}
    		if(trim($claimees_str) == ''){
    			$claimees_str = $this->Auth->user('id');
    		} else {
    			$claimees_str = $claimees_str.','.$this->Auth->user('id');
    		}


$this->loadModel('Claim');
$data['Claim']['user_id'] = $this->Auth->user('id');
$data['Claim']['listing_id'] = $id;
$data['Claim']['name'] = $this->data['Listing']['name'];
$data['Claim']['telephone'] = $this->data['Listing']['telephone'];
$data['Claim']['comment'] = $this->data['Listing']['comment'];
$this->Claim->create();
if($this->Claim->save($data)){
$this->Listing->id = $id;
    		$this->Listing->saveField('claim_by_users', $claimees_str);
    		$this->Session->setFlash('Your claim has submitted.');
    		$this->redirect('/');
} else {
    		$this->Session->setFlash('Unable to process your request. Please try again.');
    		$this->redirect($this->referer());
}
    	} else if($id && $claim && $claim == 'approve'){
$this->loadModel('Claim');

$tmp_list = $this->Claim->read(null, $id);
$this->Listing->id = $tmp_list['Claim']['listing_id'];
$this->Listing->saveField('edit_permission', $tmp_list['Claim']['user_id']);

    		$this->Claim->id = $id;
    		$this->Claim->saveField('status', 1);
    		$this->Session->setFlash('Approved.');
    		$this->redirect($this->referer());
    	} else if($id && $claim && $claim == 'disapprove'){
$this->loadModel('Claim');

$tmp_list = $this->Claim->read(null, $id);
$this->Listing->id = $tmp_list['Claim']['listing_id'];
$this->Listing->saveField('edit_permission', '');

    		$this->Claim->id = $id;
    		$this->Claim->saveField('status', 0);

    		$this->Session->setFlash('Disapproved.');
    		$this->redirect($this->referer());
    	}

        $this->Listing->set($this->data);
        $this->Listing->setValidation('submit');
        $fields_to_save = array(
            'is_active',
            'location_id', 'category_id',
            'title', 'url_title', 'description',
            'url', 'email',
            'landline', 'mobile', 'postcode', 'address_1', 'address_2', 'train_stations', 'bus_stations', 'subway_stations', 'claim_by_users', 'added_by_user_group', 'added_by_user_id', 'edit_permission',
            'opening_day', 'opening_hour_start', 'opening_hour_end', 'payment_method', 'good_for', 'access', 'year_established', 'number_of_employee', 'video', 'photo', 'streetview'
        );

        if (!empty($this->data)) {

            $opening_day = array();
            $opening_hour_start = array();
            $opening_hour_end = array();

            foreach( $this->data['Listing']['opening_day'] as $value ){
                    $opening_day[] = $value;
            }
            $this->data['Listing']['opening_day'] = implode(',', $opening_day );
            foreach( $this->data['Listing']['opening_hour_start'] as $v1){
                    $opening_hour_start[] = $v1;
            }
            $this->data['Listing']['opening_hour_start'] = implode(',', $opening_hour_start);
            foreach( $this->data['Listing']['opening_hour_end'] as $v2 ){
                    $opening_hour_end[] = $v2;
            }
            
            
            $this->data['Listing']['opening_hour_end'] = implode(',', $opening_hour_end);

            if (!empty($this->data['Listing']['payment_method'])){  
              $payment_method = $this->data['Listing']['payment_method'];            
              $payment_method = implode(',', $payment_method );
              $this->data['Listing']['payment_method'] = $payment_method;
            }
            else{
              $this->data['Listing']['payment_method'] = '';
            }

            if (!empty($this->data['Listing']['good_for'])){  
              $good_for = $this->data['Listing']['good_for'];
              $good_for = implode(',', $good_for );
              $this->data['Listing']['good_for'] = $good_for;
            }
            else{
              $this->data['Listing']['good_for'] = '';
            } 

            if (!empty($this->data['Listing']['access'])){ 
              $access = $this->data['Listing']['access'];
              $access = implode(',', $access );
              $this->data['Listing']['access'] = $access;
            }
            else{
              $this->data['Listing']['access'] = '';
            }

            if( isset( $this->data['Listing']['photo'][0]['tmp_name'] ) && !empty($this->data['Listing']['photo'][0]['tmp_name']) ) {
                    $files = array();
                    foreach($this->data['Listing']['photo'] as $key=>$value){
                            move_uploaded_file($value['tmp_name'],WWW_ROOT.'/uploads/'.$value['name']);
                            $files[] = $value['name'];
                    }
                    $this->data['Listing']['photo'] = implode(',', $files);
            }
                        

            $latlng=$this->getLatLong($this->data["Listing"]["address_1"]);
            $latlng2=split(',',$latlng);
            // Get Street View Image
            $this->data['Listing']['streetview']=$this->getStreetViewImage($latlng2[0],$latlng2[1]);
            //------------Start Get Nearby Streets
             $url2='http://maps.googleapis.com/maps/api/directions/json?origin='.$latlng.'&destination=Elgin,UK&sensor=false';
                $geocode = file_get_contents($url2);
                $output = json_decode($geocode);
                $output = $output->routes[0];

                $output = $output->legs[0];
                $output = $output->steps;
                $vicinity='';
                $old='';
                $count=0;
                 for ($i = 0; $i < count($output); $i++) { 
                    if($count<3){
                    $out=$output[$i]->html_instructions;
                    $out=  split('<b>', $out);
                    $out=$out[2];
                    $out=  split('</b>', $out);
                    $out=$out[0];
                    $address=split(' ',$out);
                    if(strpos($listing['Listing']['address_1'], $address[0])===false && $old!=$out){
                            $vicinity=$vicinity.'<br/>'.$out;
                            $old=$out;
                    }
                    else{
                            $count--;
                        }
                    $count=$count+1;
                    }
                    
                }
                
            $this->data['Listing']['nearbystreets']=  addslashes($vicinity);
           //------------End Get Nearby Streets
            $strkeywords='';
            $paths=$this->Listing->Category->getPath($this->data["Listing"]["category_id"]);
            foreach($paths as $path){
                $strkeywords=$strkeywords.','. $path['Category']['name'];
            }
            $this->data["Listing"] = $this->__trimData($this->data["Listing"]);

            if ($this->Listing->validates()) {
                $this->data["Listing"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Listing"]["title"], "UTF-8"), "-");

                $this->Listing->create();
                $this->data['Listing']['added_by_user_group'] = $this->Auth->user('group_id');
                $this->data['Listing']['added_by_user_id'] = $this->Auth->user('id');
                
                //tuannguyen2042 added 02/12/2014                
                //$this->data['Listing']['edit_permission'] = '';
                //$this->data['Listing']['is_active'] = 0;
                $this->data['Listing']['claim_by_users'] = '';
                if (is_array($this->data['Listing']['photo']))
                  $this->data['Listing']['photo'] = '';

                if (empty($this->data['Listing']['year_established']))
                  $this->data['Listing']['year_established'] = 0;

				if (empty($this->data['Listing']['number_of_employee']))
                  $this->data['Listing']['number_of_employee'] = 0;

				//print_r($fields_to_save); echo '<br/><br/>';
                //print_r($this->data); 
                //end

                if ($this->Listing->save($this->data, true, $fields_to_save)) {
               
                    $tagsTextString = trim($this->data["Listing"]["tags_text"], " ,\t\n\r\0\x0B");
                    if (!empty($tagsTextString)) {
                        $tagsTextString=$tagsTextString.$strkeywords;
                        $tagsTextExploded = explode(",", $tagsTextString);

                        foreach ($tagsTextExploded as $currentListingTagName) {
                            $currentListingTagName = trim($currentListingTagName, " ,\t\n\r\0\x0B");
                            if ($currentListingTagName != "") {
                                // insert tag
                                $checkQueryInsertTag = $this->Listing->query("
									SELECT
										count(1) AS `total`
									FROM
										`listing_tags`
									WHERE
										`name` = '" . mysql_real_escape_string($currentListingTagName) . "'
											OR
										`url_title` = '" . mysql_real_escape_string(Inflector::slug(mb_strtolower($currentListingTagName, "UTF-8"), "-")) . "'
								", false);
                                if (empty($checkQueryInsertTag[0][0]["total"])) {
                                    $this->Listing->query("
										INSERT INTO `listing_tags`(
											`created`,
											`modified`,
											`url_title`,
											`name`
										)
										VALUES(
											NOW(),
											NOW(),
											'" . mysql_real_escape_string(Inflector::slug(mb_strtolower($currentListingTagName, "UTF-8"), "-")) . "',
											'" . mysql_real_escape_string($currentListingTagName) . "'
										)
									", false);
                                }

                                // find listing_tag_id
                                $listing_tag_id_Query = $this->Listing->query("
									SELECT
										`id`
									FROM
										`listing_tags`
									WHERE
										`url_title` = '" . mysql_real_escape_string(Inflector::slug(mb_strtolower($currentListingTagName, "UTF-8"), "-")) . "'
											AND
										`name` = '" . mysql_real_escape_string($currentListingTagName) . "'
								", false);

                                // insert association
                                if (!empty($listing_tag_id_Query[0]["listing_tags"]["id"])) {
                                    // check for duplicates
                                    $checkQueryInsertAssociation = $this->Listing->query("
										SELECT
											count(1) AS `total`
										FROM
											`listing_tags_listings`
										WHERE
											`listing_tag_id` = '" . mysql_real_escape_string($listing_tag_id_Query[0]["listing_tags"]["id"]) . "'
												AND
											`listing_id` = '" . mysql_real_escape_string($this->Listing->id) . "'
									", false);

                                    if (empty($checkQueryInsertAssociation[0][0]["total"])) {
                                        $this->Listing->query("
											INSERT INTO `listing_tags_listings`(
												`listing_tag_id`,
												`listing_id`
											)
											VALUES(
												'" . mysql_real_escape_string($listing_tag_id_Query[0]["listing_tags"]["id"]) . "',
												'" . mysql_real_escape_string($this->Listing->id) . "'
											)
										", false);
                                    }
                                }
                            }
                        }
                    }

                    $this->Session->setFlash('Dani submit');
                    $this->redirect('/');
                } else {
                    $this->Session->setFlash('The listing could not be saved. Please, try again.');
                    if($id){
                    $this->redirect('claim/'.$id);
                    }
                }
            } else {
                $this->Session->setFlash('Открихме грешка!');
                if($id){
                    $this->redirect('claim/'.$id);
                    }
            }
        }

        $locations = $this->Listing->Location->find('list', array(
            'conditions' => array('Location.parent_id' => 0),
            'order' => array('Location.name ASC')
                ));

        $categories = $this->Listing->Category->find('list', array(
            'conditions' => array(
                'Category.parent_id' => 0
            ),
            'order' => array('Category.name ASC')
                ));
        $this->set(compact('locations', 'categories'));
    }


    function claim($id=null, $type=null ) {

   			if($id){
				if($type == 'claim'){
					$this->set('claim', true);
					$this->set('listing', $id);
				}
			}

        $this->Listing->recursive = -1;
        	$this->data = $this->Listing->read(null, $id);
            $payment_method = $this->data['Listing']['payment_method'];
            $payment_method = explode(',', $payment_method );
            $this->data['Listing']['payment_method'] = $payment_method;

            $good_for = $this->data['Listing']['good_for'];
            $good_for = explode(',', $good_for );
            $this->data['Listing']['good_for'] = $good_for;

            $access = $this->data['Listing']['access'];
            $access = explode(',', $access );
            $this->data['Listing']['access'] = $access;


        $locations = $this->Listing->Location->find('list', array(
            'conditions' => array('Location.parent_id' => 0),
            'order' => array('Location.name ASC')
                ));

        $categories = $this->Listing->Category->find('list', array(
            'conditions' => array(
                'Category.parent_id' => 0
            ),
            'order' => array('Category.name ASC')
                ));
        $this->set(compact('locations', 'categories'));


    }

    function submit_getfirstchildcategories($parent_id = null, $html_select_id = 'levelXCategoriesSelect') {
        $this->layout = 'ajax';
        Configure::write('debug', 0);

        if (!$parent_id) {
            return array();
        }

        $subcategories = array();
        $this->Listing->recursive = -1;
        $this->Listing->Category->recursive = -1;

        $parent_id = (int) $parent_id;

        $childrens = $this->Listing->Category->find('all', array(
            'conditions' => array(
                'Category.parent_id' => $parent_id
            ),
            'order' => array(
                'Category.name ASC'
            )
                ));

        for ($i = 0, $childrensCount = count($childrens); $i < $childrensCount; $i++) {
            $subcategories[$childrens[$i]["Category"]["id"]] = $childrens[$i]["Category"]["name"];
        }

        $data[0] = $subcategories;
        $data[1] = $html_select_id;

        $this->set('data', $data);
    }

    function submit_getsubcategories($parent_id = null) {
        $this->layout = 'ajax';
        Configure::write('debug', 0);

        if (!$parent_id) {
            exit;
        }

        $parent_id = (int) $parent_id;

        $this->set('subcategories', $this->__generateTreeListRecursive($parent_id));
    }

    // NEED REFUCTORING WHEN CakePHP _WILL_ support recursive generateTreeList()
    function __generateTreeListRecursive($parent_id, $spacer = '-') {
        if (!$parent_id) {
            return array();
        }

        $subcategories = array();
        $this->Listing->recursive = -1;
        $this->Listing->Category->recursive = -1;

        $level0__parent_id = $parent_id;
        $level0__childrens = $this->Listing->Category->find('all', array(
            'conditions' => array(
                'Category.parent_id' => $level0__parent_id
            ),
            'order' => array(
                'Category.name ASC'
            )
                ));
        if (!empty($level0__childrens)) {
            $level0__spacerLevel = 0;
            for ($level0__i = 0, $level0__childrensCount = count($level0__childrens); $level0__i < $level0__childrensCount; $level0__i++) {
                $childrenName = '';
                for ($s = 0; $s < $level0__spacerLevel; $s++) {
                    $childrenName .= $spacer;
                }
                $childrenName .= $level0__childrens[$level0__i]["Category"]["name"];
                $subcategories[$level0__childrens[$level0__i]["Category"]["id"]] = $childrenName;

                // ----- LEVEL 1
                $level1__parent_id = $level0__childrens[$level0__i]["Category"]["id"];
                $level1__childrens = $this->Listing->Category->find('all', array(
                    'conditions' => array(
                        'Category.parent_id' => $level1__parent_id
                    ),
                    'order' => array(
                        'Category.name ASC'
                    )
                        ));
                if (!empty($level1__childrens)) {
                    $level1__spacerLevel = 1;

                    for ($level1__i = 0, $level1__childrensCount = count($level1__childrens); $level1__i < $level1__childrensCount; $level1__i++) {
                        $childrenName = '';
                        for ($s = 0; $s < $level1__spacerLevel; $s++) {
                            $childrenName .= $spacer;
                        }
                        $childrenName .= $level1__childrens[$level1__i]["Category"]["name"];
                        $subcategories[$level1__childrens[$level1__i]["Category"]["id"]] = $childrenName;

                        // ----- LEVEL 2
                        $level2__parent_id = $level1__childrens[$level1__i]["Category"]["id"];
                        $level2__childrens = $this->Listing->Category->find('all', array(
                            'conditions' => array(
                                'Category.parent_id' => $level2__parent_id
                            ),
                            'order' => array(
                                'Category.name ASC'
                            )
                                ));
                        if (!empty($level2__childrens)) {
                            $level2__spacerLevel = 2;

                            for ($level2__i = 0, $level2__childrensCount = count($level2__childrens); $level2__i < $level2__childrensCount; $level2__i++) {
                                $childrenName = '';
                                for ($s = 0; $s < $level2__spacerLevel; $s++) {
                                    $childrenName .= $spacer;
                                }
                                $childrenName .= $level2__childrens[$level2__i]["Category"]["name"];
                                $subcategories[$level2__childrens[$level2__i]["Category"]["id"]] = $childrenName;

                                // ----- LEVEL 3
                                $level3__parent_id = $level2__childrens[$level2__i]["Category"]["id"];
                                $level3__childrens = $this->Listing->Category->find('all', array(
                                    'conditions' => array(
                                        'Category.parent_id' => $level3__parent_id
                                    ),
                                    'order' => array(
                                        'Category.name ASC'
                                    )
                                        ));
                                if (!empty($level3__childrens)) {
                                    $level3__spacerLevel = 3;

                                    for ($level3__i = 0, $level3__childrensCount = count($level3__childrens); $level3__i < $level3__childrensCount; $level3__i++) {
                                        $childrenName = '';
                                        for ($s = 0; $s < $level3__spacerLevel; $s++) {
                                            $childrenName .= $spacer;
                                        }
                                        $childrenName .= $level3__childrens[$level3__i]["Category"]["name"];
                                        $subcategories[$level3__childrens[$level3__i]["Category"]["id"]] = $childrenName;

                                        // ----- LEVEL 4
                                        $level4__parent_id = $level3__childrens[$level3__i]["Category"]["id"];
                                        $level4__childrens = $this->Listing->Category->find('all', array(
                                            'conditions' => array(
                                                'Category.parent_id' => $level4__parent_id
                                            ),
                                            'order' => array(
                                                'Category.name ASC'
                                            )
                                                ));
                                        if (!empty($level4__childrens)) {
                                            $level4__spacerLevel = 4;

                                            for ($level4__i = 0, $level4__childrensCount = count($level4__childrens); $level4__i < $level4__childrensCount; $level4__i++) {
                                                $childrenName = '';
                                                for ($s = 0; $s < $level4__spacerLevel; $s++) {
                                                    $childrenName .= $spacer;
                                                }
                                                $childrenName .= $level4__childrens[$level4__i]["Category"]["name"];
                                                $subcategories[$level4__childrens[$level4__i]["Category"]["id"]] = $childrenName;

                                                // ----- LEVEL 5
                                                $level5__parent_id = $level4__childrens[$level4__i]["Category"]["id"];
                                                $level5__childrens = $this->Listing->Category->find('all', array(
                                                    'conditions' => array(
                                                        'Category.parent_id' => $level5__parent_id
                                                    ),
                                                    'order' => array(
                                                        'Category.name ASC'
                                                    )
                                                        ));
                                                if (!empty($level5__childrens)) {
                                                    $level5__spacerLevel = 5;

                                                    for ($level5__i = 0, $level5__childrensCount = count($level5__childrens); $level5__i < $level5__childrensCount; $level5__i++) {
                                                        $childrenName = '';
                                                        for ($s = 0; $s < $level5__spacerLevel; $s++) {
                                                            $childrenName .= $spacer;
                                                        }
                                                        $childrenName .= $level5__childrens[$level5__i]["Category"]["name"];
                                                        $subcategories[$level5__childrens[$level5__i]["Category"]["id"]] = $childrenName;

                                                        // ----- LEVEL 6
                                                        $level6__parent_id = $level5__childrens[$level5__i]["Category"]["id"];
                                                        $level6__childrens = $this->Listing->Category->find('all', array(
                                                            'conditions' => array(
                                                                'Category.parent_id' => $level6__parent_id
                                                            ),
                                                            'order' => array(
                                                                'Category.name ASC'
                                                            )
                                                                ));
                                                        if (!empty($level6__childrens)) {
                                                            $level6__spacerLevel = 6;

                                                            for ($level6__i = 0, $level6__childrensCount = count($level6__childrens); $level6__i < $level6__childrensCount; $level6__i++) {
                                                                $childrenName = '';
                                                                for ($s = 0; $s < $level6__spacerLevel; $s++) {
                                                                    $childrenName .= $spacer;
                                                                }
                                                                $childrenName .= $level6__childrens[$level6__i]["Category"]["name"];
                                                                $subcategories[$level6__childrens[$level6__i]["Category"]["id"]] = $childrenName;

                                                                // ----- LEVEL 7
                                                                $level7__parent_id = $level6__childrens[$level6__i]["Category"]["id"];
                                                                $level7__childrens = $this->Listing->Category->find('all', array(
                                                                    'conditions' => array(
                                                                        'Category.parent_id' => $level7__parent_id
                                                                    ),
                                                                    'order' => array(
                                                                        'Category.name ASC'
                                                                    )
                                                                        ));
                                                                if (!empty($level7__childrens)) {
                                                                    $level7__spacerLevel = 7;

                                                                    for ($level7__i = 0, $level7__childrensCount = count($level7__childrens); $level7__i < $level7__childrensCount; $level7__i++) {
                                                                        $childrenName = '';
                                                                        for ($s = 0; $s < $level7__spacerLevel; $s++) {
                                                                            $childrenName .= $spacer;
                                                                        }
                                                                        $childrenName .= $level7__childrens[$level7__i]["Category"]["name"];
                                                                        $subcategories[$level7__childrens[$level7__i]["Category"]["id"]] = $childrenName;

                                                                        // ----- LEVEL 8
                                                                        $level8__parent_id = $level7__childrens[$level7__i]["Category"]["id"];
                                                                        $level8__childrens = $this->Listing->Category->find('all', array(
                                                                            'conditions' => array(
                                                                                'Category.parent_id' => $level8__parent_id
                                                                            ),
                                                                            'order' => array(
                                                                                'Category.name ASC'
                                                                            )
                                                                                ));
                                                                        if (!empty($level8__childrens)) {
                                                                            $level8__spacerLevel = 8;

                                                                            for ($level8__i = 0, $level8__childrensCount = count($level8__childrens); $level8__i < $level8__childrensCount; $level8__i++) {
                                                                                $childrenName = '';
                                                                                for ($s = 0; $s < $level8__spacerLevel; $s++) {
                                                                                    $childrenName .= $spacer;
                                                                                }
                                                                                $childrenName .= $level8__childrens[$level8__i]["Category"]["name"];
                                                                                $subcategories[$level8__childrens[$level8__i]["Category"]["id"]] = $childrenName;

                                                                                // ----- LEVEL 9
                                                                                $level9__parent_id = $level8__childrens[$level8__i]["Category"]["id"];
                                                                                $level9__childrens = $this->Listing->Category->find('all', array(
                                                                                    'conditions' => array(
                                                                                        'Category.parent_id' => $level9__parent_id
                                                                                    ),
                                                                                    'order' => array(
                                                                                        'Category.name ASC'
                                                                                    )
                                                                                        ));
                                                                                if (!empty($level9__childrens)) {
                                                                                    $level9__spacerLevel = 9;

                                                                                    for ($level9__i = 0, $level9__childrensCount = count($level9__childrens); $level9__i < $level9__childrensCount; $level9__i++) {
                                                                                        $childrenName = '';
                                                                                        for ($s = 0; $s < $level9__spacerLevel; $s++) {
                                                                                            $childrenName .= $spacer;
                                                                                        }
                                                                                        $childrenName .= $level9__childrens[$level9__i]["Category"]["name"];
                                                                                        $subcategories[$level9__childrens[$level9__i]["Category"]["id"]] = $childrenName;

                                                                                        // ----- LEVEL 10
                                                                                        $level10__parent_id = $level9__childrens[$level9__i]["Category"]["id"];
                                                                                        $level10__childrens = $this->Listing->Category->find('all', array(
                                                                                            'conditions' => array(
                                                                                                'Category.parent_id' => $level10__parent_id
                                                                                            ),
                                                                                            'order' => array(
                                                                                                'Category.name ASC'
                                                                                            )
                                                                                                ));
                                                                                        if (!empty($level10__childrens)) {
                                                                                            $level10__spacerLevel = 10;

                                                                                            for ($level10__i = 0, $level10__childrensCount = count($level10__childrens); $level10__i < $level10__childrensCount; $level10__i++) {
                                                                                                $childrenName = '';
                                                                                                for ($s = 0; $s < $level10__spacerLevel; $s++) {
                                                                                                    $childrenName .= $spacer;
                                                                                                }
                                                                                                $childrenName .= $level10__childrens[$level10__i]["Category"]["name"];
                                                                                                $subcategories[$level10__childrens[$level10__i]["Category"]["id"]] = $childrenName;
                                                                                            } // for($level10__i = 0, $level10__childrensCount = count($level10__childrens); $level10__i < $level10__childrensCount; $level10__i++)
                                                                                        }
                                                                                    } // for($level9__i = 0, $level9__childrensCount = count($level9__childrens); $level9__i < $level9__childrensCount; $level9__i++)
                                                                                }
                                                                            } // for($level8__i = 0, $level8__childrensCount = count($level8__childrens); $level8__i < $level8__childrensCount; $level8__i++)
                                                                        }
                                                                    } // for($level7__i = 0, $level7__childrensCount = count($level7__childrens); $level7__i < $level7__childrensCount; $level7__i++)
                                                                }
                                                            } // for($level6__i = 0, $level6__childrensCount = count($level6__childrens); $level6__i < $level6__childrensCount; $level6__i++)
                                                        }
                                                    } // for($level5__i = 0, $level5__childrensCount = count($level5__childrens); $level5__i < $level5__childrensCount; $level5__i++)
                                                }
                                            } // for($level4__i = 0, $level4__childrensCount = count($level4__childrens); $level4__i < $level4__childrensCount; $level4__i++)
                                        }
                                    } // for($level3__i = 0, $level3__childrensCount = count($level3__childrens); $level3__i < $level3__childrensCount; $level3__i++)
                                }
                            } // for($level2__i = 0, $level2__childrensCount = count($level2__childrens); $level2__i < $level2__childrensCount; $level2__i++)
                        }
                    } // for($level1__i = 0, $level1__childrensCount = count($level1__childrens); $level1__i < $level1__childrensCount; $level1__i++)
                }
            } // for($level0__i = 0, $level0__childrensCount = count(); $level0__i < $level0__childrensCount; $level0__i++)
        }

        return $subcategories;
    }

    function admin_index_all($type=null) {

  	if($type == "claims"){

$this->loadModel('Claim');

        $this->set('claims', $this->paginate('Claim'));
	$this->set('claimView', true);
	} else {
        $this->Listing->recursive = 0;
        $this->set('listings', $this->paginate('Listing'));
	}

}

    function admin_index_new() {
        $this->Listing->recursive = 0;
        $this->set('listings', $this->paginate('Listing', array('Listing.is_active' => 0)));
    }

    function admin_edit($id = null) {
        $this->Listing->idFieldValue = $id;
        $this->Listing->set($this->data);
        $this->Listing->setValidation('admin_edit');
        $fields_to_save = array(
            'is_active', 'location_id', 'category_id',
            'title', 'url_title', 'description',
            'url', 'email',
            'landline', 'mobile', 'postcode',
            'address_1', 'address_2'
        );

        if (!$id && empty($this->data)) {
            $this->Session->setFlash('Invalid listing');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listings', 'action' => 'index_all'));
        }
        if (!empty($this->data)) {
            $this->data["Listing"] = $this->__trimData($this->data["Listing"]);

            if ($this->Listing->validates()) {
                $this->data["Listing"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Listing"]["title"], "UTF-8"), "-");

                if ($this->Listing->save($this->data, true, $fields_to_save)) {
                    $this->Session->setFlash('Листинга е запаметен успешно');
                    $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listings', 'action' => 'index_all'));
                } else {
                    $this->Session->setFlash('The listing could not be saved. Please, try again.');
                }
            } else {
                $this->Session->setFlash('Грешка');
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Listing->read(null, $id);
        }
        $locations = $this->Listing->Location->find('list');
        $categories = $this->Listing->Category->generateTreeList(null, null, null, '-', null);
        $listingTags = $this->Listing->ListingTag->find('list');
        $this->set(compact('locations', 'categories', 'listingTags'));
    }

    function admin_delete($id = null) {
        if (!$id) {
            $this->Session->setFlash('Invalid listing');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listings', 'action' => 'index_all'));
        }
        if ($this->Listing->delete($id)) {
            $this->Session->setFlash('Листинга е изтрит успешно');
            $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listings', 'action' => 'index_all'));
        }
        $this->Session->setFlash('Грешка');
        $this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'listings', 'action' => 'index_all'));
    }

    function review() {
        Configure::write('debug', 0);
        $this->layout = false;
        // Save review
        if ($this->data['Review']) {
            $this->data['Review']['rate'] = $_REQUEST['rate'];
            $this->data['Review']['created'] = date('Y-m-d H:i:s');
            $this->data['Review']['status'] = 0;
             $this->data['Review']['user_id'] = $this->Auth->user('id');
            $this->Review->save($this->data);
            echo json_encode(array('i_Code' => 1));
        } else {
            echo json_encode(array('i_Code' => 0));
        }

        $this->render(false);
    }

    function submit_getsublocations($parent_id = null) {
        $this->layout = 'ajax';
        Configure::write('debug', 0);

        if (!$parent_id) {
            exit;
        }
        $parent_id = (int) $parent_id;

        $locations = $this->Location->find('all', array('conditions' => array('Location.parent_id' => $parent_id), 'order' => 'Location.name'));
        $this->set(compact('locations'));
    }

}